package com.dgut.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.dgut.common.excetion.GlobalSystemException;
import com.dgut.common.model.entity.LoginUser;
import com.dgut.common.model.entity.User;
import com.dgut.common.service.UserService;
import com.dgut.common.util.GlobalResponseCode;
import com.dgut.common.util.JwtUtil;
import com.dgut.common.util.SystemJsonResponse;
import com.dgut.service.AuthService;

/**
 * @author huangyujia <huangyujia@kuaishou.com>
 * Created on 2024-06-18
 */
@Service
public class AuthServiceImpl implements AuthService, UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Override
    public SystemJsonResponse login(String userName, String password) {
        //后台管理密码,
        UsernamePasswordAuthenticationToken authenticationToken=
                new UsernamePasswordAuthenticationToken(userName,password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        //密码或者账号不对
        if(Objects.isNull(authenticate)) {
            throw new GlobalSystemException(
                    GlobalResponseCode.ACCOUNT_NOT_EXIST.getCode(),
                    GlobalResponseCode.ACCOUNT_NOT_EXIST.getMessage());
        }
        String jwt = JwtUtil.createJWT(userName);

        return  SystemJsonResponse.success(jwt);
    }

    /**
     * 查询数据库校验权限和账户密码
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userService.getByUserName(userName);
        List<String> permission = new ArrayList<>();
        if (user == null) {
            throw new GlobalSystemException(
                    GlobalResponseCode.ACCOUNT_NOT_EXIST.getCode(),
                    GlobalResponseCode.ACCOUNT_NOT_EXIST.getMessage());
        }
        return new LoginUser(user, permission);
    }

}
